package com.hotec.PROJECT_NAME.config.security.impl;

import cn.hutool.core.util.StrUtil;
import com.hotec.PROJECT_NAME.component.exception.exc.BizException;
import com.hotec.PROJECT_NAME.config.security.token.AdminUsernamePasswordAuthenticationToken;
import com.hotec.PROJECT_NAME.config.security.token.MobileAndCodeToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeUnit;

/**
 * 自定义身份认证验证组件
 *
 * @author
 */
@Component
public class CustomAuthenticationProvider implements AuthenticationProvider {

    @Autowired
    @Qualifier("userDetailsServiceImpl")
    private UserDetailsService userDetailsService;

    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        // 获取认证的用户名
        String name = StrUtil.trim(authentication.getName());

        int integer = Integer.parseInt(StrUtil.nullToDefault(stringRedisTemplate.opsForValue().get(name), "1"));

        if(integer >= 5 || integer == -1){
            if(integer != -1) stringRedisTemplate.opsForValue().set(name, "-1", 30, TimeUnit.MINUTES);

            throw new BizException("密码错误次数过多，请30分钟后重试");
        }

        try {
            UserDetails userDetails = userDetailsService.loadUserByUsername(name);

            if(authentication instanceof MobileAndCodeToken){
                return new UsernamePasswordAuthenticationToken(userDetails.getUsername(), null, userDetails.getAuthorities());
            }

            String password = StrUtil.trim(StrUtil.str(authentication.getCredentials(), StandardCharsets.UTF_8));

            if (bCryptPasswordEncoder.matches(password, userDetails.getPassword())) {
                return new UsernamePasswordAuthenticationToken(userDetails.getUsername(), password, userDetails.getAuthorities());
            } else {
                throw new BizException("用户名或密码错误");
            }
        } catch (Exception ex) {
            if(ex.getMessage().startsWith("用户名或密码错误")){
                stringRedisTemplate.opsForValue().set(name, String.valueOf(integer + 1), 5, TimeUnit.MINUTES);

                throw new BizException(StrUtil.format("用户名或密码错误，剩余{}次机会", 5 - integer));
            }

            throw ex;
        }
    }

    /**
     * 是否可以提供输入类型的认证服务
     *
     * @param authentication
     * @return
     */
    @Override
    public boolean supports(Class<?> authentication) {
        return authentication.equals(MobileAndCodeToken.class) ||
                authentication.equals(AdminUsernamePasswordAuthenticationToken.class);
    }

}
